package cn.kxm.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import cn.kxm.dao.CheckTheNewCode;
@Component
public class MakeNewCode {
	/**
	 * 根据前缀返回编码
	 * @param prefix
	 * @return
	 */
	private  Map<String, String> tableMap;
	@Autowired
	private  CheckTheNewCode dtnc;
	
	{
		tableMap=new HashMap<String, String>();
		tableMap.put("BJ", "offerpricebill");
		tableMap.put("FK", "paybill");
		tableMap.put("XS", "sellorderbill");
		tableMap.put("CK", "outstoragebill");
		tableMap.put("RK", "instroageBill");
		tableMap.put("CG", "purchaseOrderBill");
		tableMap.put("KX", "company");
		tableMap.put("SK", "collectbill");
		tableMap.put("IQ", "inquirybill");
		tableMap.put("XJ", "part");
	}
	
	
	public  String getRandomCodeByPrefix(String prefix){
		String code="";
		Date date=new Date();
		DateFormat format = new SimpleDateFormat("yyyyMMdd"); 
		String time = format.format(date);
		String temp=new String(new Random().nextLong()+"");
		String randomCode=temp.substring(temp.length()-6, temp.length());
		code+=prefix;
		code+=time;
		code+=randomCode;
		
		if(isRepeat(code)){
			code=getRandomCodeByPrefix(prefix);
			return code;
		}else{
			return code;
		}
	}
	
	public boolean isRepeat(String code){
		String prefix=code.substring(0, 2);
		int count=dtnc.getCount(tableMap.get(prefix), code);
		if(count==0){
			return false;
		}else{
			return true;
		}
	}
}
